package com.bee.shepherd.common.handler;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.bee.shepherd.common.handler.JacksonHandler;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

import freemarker.template.Configuration;
import freemarker.template.Template;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.Authenticator;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * apache方式的邮件服务
 */
//@Service
public class MailHandler implements InitializingBean {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String DEFAULT_CHARSET = "UTF-8";

    @Value("${mail.from}")
    private String mailFrom;

    @Value("${mail.hosts}")
    private String mailHost;

    @Value("${mail.pwd}")
    private String pwd;

    @Value("${mail.user}")
    private String user;

    private Authenticator authenticator;

    @Autowired
    private Configuration configuration;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.authenticator = new DefaultAuthenticator(user, pwd);
    }

    private HtmlEmail generateBaseEmail(String subject,List<String> toList,List<String> ccList)throws EmailException{
        HtmlEmail email = new HtmlEmail();
        email.setCharset(DEFAULT_CHARSET);
        email.setHostName(mailHost);
        email.setStartTLSEnabled(true);
        email.setAuthenticator(authenticator);
        email.setFrom(mailFrom);
        email.setSubject(subject);
        if (toList!=null && CollectionUtils.size(toList)>0){
            email.addTo(toList.toArray(new String[toList.size()]));
        }
        if (ccList!=null && CollectionUtils.size(ccList)>0){
            email.addCc(ccList.toArray(new String[ccList.size()]));
        }
        return email;
    }

    /**
     * 简易发邮件
     * @param params       参数
     * @param templateName 模板名称
     * @param subject      主题
     * @param toEmails      to
     * @param ccEmails      cc
     */
    public void sendSimpleEmail(Map<String, Object> params, String templateName, String subject,
                                List<String> toEmails,List<String> ccEmails) throws Exception {
        logger.info("sendSimpleEmail toList={},ccList={}", JacksonHandler.toSerialize(toEmails),JacksonHandler.toSerialize(ccEmails));
        HtmlEmail email = generateBaseEmail(subject,toEmails,ccEmails);
        //todo demo
        String content=generateContent();
        email.setHtmlMsg(content);
        email.send();
    }

    private String generateContent(){
        try {
            Map<String,Object> dataModel = new HashMap<>();
            dataModel.put("testUser","你好");
            Template template = configuration.getTemplate("demo.ftl");
            //todo
            StringWriter stringWriter=new StringWriter();
            template.process(dataModel,stringWriter);
            String ttt = stringWriter.getBuffer().toString();
            //todo
            System.out.println(ttt);
            return ttt;
        }catch (Exception e){
            logger.error("generateContent error",e);
            return null;
        }
    }

    /**
     * 发送邮件+附件
     */
    public void sendEmailWithAttachment(List<String> toList,String subject,String content, List<File> attachments) {
        logger.info("sendEmailWithAttachment,toList={},subject={},content={},attachments={}",
                JacksonHandler.toSerialize(toList), subject, content, attachments);
        Preconditions.checkArgument(CollectionUtils.isNotEmpty(toList), "收邮件人列表不能为空");
        try {
            HtmlEmail email = generateBaseEmail(subject, toList, Lists.newArrayList());
            email.setMsg(content);
            if (CollectionUtils.isNotEmpty(attachments)) {
                for (File file : attachments) {
                    EmailAttachment emailAttachment = new EmailAttachment();
                    emailAttachment.setPath(file.getPath());
                    emailAttachment.setName(new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
                    email.attach(emailAttachment);
                }
            } else {
                logger.info("附件为空");
            }
            email.send();
        } catch (Exception e) {
            logger.error("sendEmailWithAttachment error", e);
            throw new RuntimeException("发送邮件失败");
        }
        logger.info("sendEmailWithAttachment success");
    }
}
